home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Gold Collection / Software Vault - The Gold Collection (American Databankers) (1993).ISO / cdr49 / pgp23src.zip / PGP.C < prev    next >
C/C++ Source or Header  |  1993-06-13  |  62KB  |  2,031 lines

  1. /* #define TEMP_VERSION    / * if defined, temporary experimental version of PGP */
  2. /*    pgp.c -- main module for PGP.
  3.     PGP: Pretty Good(tm) Privacy - public key cryptography for the masses.
  4.  
  5.     Synopsis:  PGP uses public-key encryption to protect E-mail. 
  6.     Communicate securely with people you've never met, with no secure
  7.     channels needed for prior exchange of keys.  PGP is well featured and
  8.     fast, with sophisticated key management, digital signatures, data
  9.     compression, and good ergonomic design.
  10.  
  11.     The original PGP version 1.0 was written by Philip Zimmermann, of
  12.     Phil's Pretty Good(tm) Software.  Many parts of later versions of 
  13.     PGP were developed by an international collaborative effort, 
  14.     involving a number of contributors, including major efforts by:
  15.         Branko Lankester <lankeste@fwi.uva.nl> 
  16.         Hal Finney <74076.1041@compuserve.com>
  17.         Peter Gutmann <pgut1@cs.aukuni.ac.nz>
  18.     Other contributors who ported or translated or otherwise helped include:
  19.         Jean-loup Gailly in France
  20.         Hugh Kennedy in Germany
  21.         Lutz Frank in Germany
  22.         Cor Bosman in The Netherlands
  23.         Felipe Rodriquez Svensson in The Netherlands
  24.         Armando Ramos in Spain
  25.         Miguel Angel Gallardo Ortiz in Spain
  26.         Harry Bush and Maris Gabalins in Latvia
  27.         Zygimantas Cepaitis in Lithuania
  28.         Alexander Smishlajev
  29.         Peter Suchkow and Andrew Chernov in Russia
  30.         David Vincenzetti in Italy
  31.         ...and others.
  32.  
  33.     Note that while many PGP source modules bear the copyright notice of
  34.     Philip Zimmermann, some of them may have been revised or in some
  35.     cases entirely written by other members of the PGP development team,
  36.     who often failed to put their names in their code.
  37.  
  38.     Revisions:
  39.         Version 1.0 - 5 Jun 91
  40.         Version 1.4 - 19 Jan 92
  41.         Version 1.5 - 12 Feb 92
  42.         Version 1.6 - 24 Feb 92
  43.         Version 1.7 - 29 Mar 92
  44.         Version 1.8 - 23 May 92
  45.         Version 2.0 - 2 Sep 92
  46.         Version 2.1 - 6 Dec 92
  47.         Version 2.2 - 6 Mar 93
  48.         Version 2.3 - 13 Jun 93
  49.  
  50.     (c) Copyright 1990-1993 by Philip Zimmermann.  All rights reserved.
  51.     The author assumes no liability for damages resulting from the use
  52.     of this software, even if the damage results from defects in this
  53.     software.  No warranty is expressed or implied.
  54.  
  55.     All the source code Philip Zimmermann wrote for PGP is available for
  56.     free under the "Copyleft" General Public License from the Free
  57.     Software Foundation.  A copy of that license agreement is included in
  58.     the source release package of PGP.  Code developed by others for PGP
  59.     is also freely available.  Other code that has been incorporated into
  60.     PGP from other sources was either originally published in the public
  61.     domain or was used with permission from the various authors.  See the
  62.     PGP User's Guide for more complete information about licensing,
  63.     patent restrictions on certain algorithms, trademarks, copyrights,
  64.     and export controls.  
  65.  
  66.     Philip Zimmermann may be reached at:
  67.         Boulder Software Engineering
  68.         3021 Eleventh Street
  69.         Boulder, Colorado 80304  USA
  70.         (303) 541-0140  (voice or FAX)
  71.         email:  prz@sage.cgd.ucar.edu
  72.  
  73.  
  74.     PGP will run on MSDOS, Sun Unix, VAX/VMS, Ultrix, Atari ST, 
  75.     Commodore Amiga, and OS/2.  Note:  Don't try to do anything with 
  76.     this source code without looking at the PGP User's Guide.
  77.  
  78.     PGP combines the convenience of the Rivest-Shamir-Adleman (RSA)
  79.     public key cryptosystem with the speed of fast conventional
  80.     cryptographic algorithms, fast message digest algorithms, data
  81.     compression, and sophisticated key management.  And PGP performs 
  82.     the RSA functions faster than most other software implementations.  
  83.     PGP is RSA public key cryptography for the masses.
  84.  
  85.     Uses RSA Data Security, Inc. MD5 Message Digest Algorithm
  86.     as a hash for signatures.  Uses the ZIP algorithm for compression.
  87.     Uses the ETH IPES/IDEA algorithm for conventional encryption.
  88.  
  89.     PGP generally zeroes its used stack and memory areas before exiting.
  90.     This avoids leaving sensitive information in RAM where other users
  91.     could find it later.  The RSA library and keygen routines also
  92.     sanitize their own stack areas.  This stack sanitizing has not been
  93.     checked out under all the error exit conditions, when routines exit
  94.     abnormally.  Also, we must find a way to clear the C I/O library
  95.     file buffers, the disk buffers, and and cache buffers.
  96.  
  97.     If you modify this code, PLEASE preserve the style of indentation
  98.     used for {begin...end} blocks.  It drives me bats to have to deal
  99.     with more than one style in the same program.
  100.  
  101.      Modified: 12-Nov-92 HAJK
  102.      Add FDL stuff for VAX/VMS local mode. 
  103. */
  104.  
  105.  
  106. #include <ctype.h>
  107. #ifndef AMIGA
  108. #include <signal.h>
  109. #endif
  110. #include <stdio.h>
  111. #include <stdlib.h>
  112. #include <string.h>
  113. #include "system.h"
  114. #include "mpilib.h"
  115. #include "random.h"
  116. #include "crypto.h"
  117. #include "fileio.h"
  118. #include "keymgmt.h"
  119. #include "language.h"
  120. #include "pgp.h"
  121. #include "exitpgp.h"
  122. #include "charset.h"
  123. #include "getopt.h"
  124. #include "config.h"
  125. #include "keymaint.h"
  126. #include "keyadd.h"
  127. #include "rsaglue.h"
  128. #ifdef  M_XENIX
  129. char *strstr();
  130. long time();
  131. #endif
  132.  
  133. #ifdef MSDOS
  134. #ifdef __ZTC__    /* Extend stack for Zortech C */
  135. unsigned _stack_ = 24*1024;
  136. #endif
  137. #ifdef __TURBOC__
  138. unsigned _stklen = 24*1024;
  139. #endif
  140. #endif
  141. #define    STACK_WIPE    4096
  142.  
  143. /* Global filenames and system-wide file extensions... */
  144. char rel_version[] = "2.3";    /* release version */
  145. #ifdef RSAREF
  146. #define RSASTRING " (with RSAREF)"
  147. #else
  148. #define RSASTRING ""
  149. #endif
  150. static char rel_date[] = "13 Jun 93";    /* release date */
  151. char PGP_EXTENSION[] = ".pgp";
  152. char ASC_EXTENSION[] = ".asc";
  153. char SIG_EXTENSION[] = ".sig";
  154. char BAK_EXTENSION[] = ".bak";
  155. static char HLP_EXTENSION[] = ".hlp";
  156. char CONSOLE_FILENAME[] = "_CONSOLE";
  157. static char HELP_FILENAME[] = "pgp.hlp";
  158.  
  159. /* These files use the environmental variable PGPPATH as a default path: */
  160. static char CONFIG_FILENAME[] = "config.txt";
  161. char PUBLIC_KEYRING_FILENAME[32] = "pubring.pgp";
  162. char SECRET_KEYRING_FILENAME[32] = "secring.pgp";
  163. char RANDSEED_FILENAME[32] = "randseed.bin";
  164.  
  165. /* Flags which are global across the driver code files */
  166. boolean verbose = FALSE;    /* -l option: display maximum information */
  167. FILE    *pgpout;            /* Place for routine messages */
  168.  
  169. static void usage(void);
  170. static void key_usage(void);
  171. static void arg_error(void);
  172. static void initsigs(void);
  173. static int do_keyopt(char);
  174. static int do_decrypt(char *);
  175. static void do_armorfile(char *);
  176.  
  177.  
  178. /*    Various compression signatures: PKZIP, Zoo, GIF, Arj, and HPACK.  
  179.     Lha(rc) is handled specially in the code; it is missing from the 
  180.     compressSig structure intentionally.  If more formats are added, 
  181.     put them before lharc to keep the code consistent. 
  182. */
  183. static char *compressSig[] =  { "PK\03\04", "ZOO ", "GIF8", "\352\140",
  184.     "HPAK", "\037\213", "\037\235", "\032\013", "\032HP%"
  185.     /* lharc is special, must be last */ };
  186. static char *compressName[] = { "PKZIP",   "Zoo",  "GIF",  "Arj",
  187.     "Hpack", "gzip", "compressed", "PAK", "Hyper",
  188.     "LHarc" };
  189. static char *compressExt[] =  { ".zip",  ".zoo",  ".gif",  ".arj",
  190.     ".hpk", ".z", ".Z", ".pak", ".hyp",
  191.     ".lzh" };
  192.  
  193. /* "\032\0??", "ARC", ".arc" */
  194.  
  195. int compressSignature(byte *header)
  196. /* Returns file signature type from a number of popular compression formats
  197.    or -1 if no match */
  198. {    int i;
  199.  
  200.     for (i=0; i<sizeof(compressSig)/sizeof(*compressSig); i++)
  201.         if (!strncmp((char *)header, compressSig[i], strlen(compressSig[i])))
  202.             return(i);
  203.     /* Special check for lharc files */
  204.     if (header[2]=='-' && header[3]=='l' && (header[4]=='z'||header[4]=='h') &&
  205.         header[6]=='-')
  206.         return(i);
  207.     return(-1);
  208. }    /* compressSignature */
  209.  
  210.  
  211. static boolean file_compressible(char *filename)
  212. {    /* returns TRUE iff file is likely to be compressible */
  213.     byte header[8];
  214.     get_header_info_from_file( filename, header, 8 );
  215.     if (compressSignature( header ) >= 0)
  216.         return (FALSE);    /* probably not compressible */
  217.     return (TRUE);    /* possibly compressible */
  218. }    /* compressible */
  219.  
  220.  
  221. /* Possible error exit codes - not all of these are used.  Note that we
  222.    don't use the ANSI EXIT_SUCCESS and EXIT_FAILURE.  To make things
  223.    easier for compilers which don't support enum we use #defines */
  224.  
  225. #define EXIT_OK                    0
  226. #define INVALID_FILE_ERROR        1
  227. #define FILE_NOT_FOUND_ERROR    2
  228. #define UNKNOWN_FILE_ERROR        3
  229. #define NO_BATCH                4
  230. #define BAD_ARG_ERROR            5
  231. #define INTERRUPT                6
  232. #define OUT_OF_MEM                7
  233.  
  234. /* Keyring errors: Base value = 10 */
  235. #define KEYGEN_ERROR            10
  236. #define NONEXIST_KEY_ERROR        11
  237. #define KEYRING_ADD_ERROR        12
  238. #define KEYRING_EXTRACT_ERROR    13
  239. #define KEYRING_EDIT_ERROR        14
  240. #define KEYRING_VIEW_ERROR        15
  241. #define KEYRING_REMOVE_ERROR    16
  242. #define KEYRING_CHECK_ERROR        17
  243. #define KEY_SIGNATURE_ERROR        18
  244. #define KEYSIG_REMOVE_ERROR        19
  245.  
  246. /* Encode errors: Base value = 20 */
  247. #define SIGNATURE_ERROR            20
  248. #define RSA_ENCR_ERROR            21
  249. #define ENCR_ERROR                22
  250. #define COMPRESS_ERROR            23
  251.  
  252. /* Decode errors: Base value = 30 */
  253. #define SIGNATURE_CHECK_ERROR    30
  254. #define RSA_DECR_ERROR            31
  255. #define DECR_ERROR                32
  256. #define DECOMPRESS_ERROR        33
  257.  
  258.  
  259. #ifdef SIGINT
  260. void breakHandler(int sig)
  261. /* This function is called if a BREAK signal is sent to the program.  In this
  262.    case we zap the temporary files.
  263. */
  264. {
  265. #ifdef UNIX
  266.     if (sig == SIGPIPE)
  267.     {    signal(SIGPIPE, SIG_IGN);
  268.         exitPGP(INTERRUPT);
  269.     }
  270.     if (sig != SIGINT)
  271.         fprintf(stderr, "\nreceived signal %d\n", sig);
  272.     else
  273. #endif
  274.         fprintf(pgpout,PSTR("\nStopped at user request\n"));
  275.     exitPGP(INTERRUPT);
  276. }
  277. #endif
  278.  
  279.  
  280. static void clearscreen(void)
  281. {    /* Clears screen and homes the cursor. */
  282.     fprintf(pgpout,"\n\033[0;0H\033[J\r           \r");    /* ANSI sequence. */
  283.     fflush(pgpout);
  284. }
  285.  
  286. static void signon_msg(void)
  287. {    /*    We had to process the config file first to possibly select the 
  288.         foreign language to translate the sign-on line that follows... */
  289.     word32 tstamp;
  290.         /* display message only once to allow calling multiple times */
  291.     static boolean printed = FALSE;
  292.  
  293.     if (quietmode || printed)
  294.         return;
  295.     printed = TRUE;
  296.     fprintf(stderr,PSTR("Pretty Good Privacy %s%s - Public-key encryption for the masses.\n"),
  297.         rel_version, RSASTRING);
  298. #ifdef TEMP_VERSION
  299.     fprintf(stderr, "Internal development version only - not for general release.\n");
  300. #endif
  301.     fprintf(stderr, PSTR("(c) 1990-1993 Philip Zimmermann, Phil's Pretty Good Software. %s\n"),
  302.         rel_date);
  303.  
  304.     get_timestamp((byte *)&tstamp);    /* timestamp points to tstamp */
  305.     fprintf(pgpout,"Date: %s\n",ctdate(&tstamp));
  306. }
  307.  
  308.  
  309. #ifdef TEMP_VERSION    /* temporary experimental version of PGP */
  310. #include <time.h>
  311. #define CREATION_DATE ((unsigned long) 0x2C18C6BCL)
  312.   /* CREATION_DATE is Fri Jun 11 17:54:04 1993 UTC */
  313. #define LIFESPAN    ((unsigned long) 30L * (unsigned long) 86400L)
  314.     /* LIFESPAN is 30 days */
  315. void check_expiration_date(void)
  316. {    /* If this is an experimental version of PGP, cut its life short */
  317.     word32 t;
  318.     t = time(NULL);
  319.     if (t > (CREATION_DATE + LIFESPAN))
  320.     {    fprintf(stderr,"\n\007This experimental version of PGP has expired.\n");
  321.         exit(-1);    /* error exit */
  322.     }
  323. }    /* check_expiration_date */
  324. #else    /* no expiration date */
  325. #define check_expiration_date() /* null statement */
  326. #endif    /* TEMP_VERSION */
  327.  
  328.  
  329.  
  330. /* -f means act as a unix-style filter */
  331. /* -i means internalize extended file attribute information, only supported
  332.  *          between like (or very compatible) operating systems. */
  333. /* -l means show longer more descriptive diagnostic messages */
  334. /* -m means display plaintext output on screen, like unix "more" */
  335. /* -d means decrypt only, leaving inner signature wrapping intact */
  336. /* -t means treat as pure text and convert to canonical text format */
  337.  
  338. /* Used by getopt function... */
  339. #define OPTIONS "abcdefghiklmo:prstu:vwxz:ABCDEFGHIKLMO:PRSTU:VWX?"
  340. extern int optind;
  341. extern char *optarg;
  342.  
  343. boolean emit_radix_64 = FALSE;        /* set by config file */
  344. static boolean sign_flag = FALSE;
  345. boolean moreflag = FALSE;
  346. boolean filter_mode = FALSE;
  347. static boolean preserve_filename = FALSE;
  348. static boolean decrypt_only_flag = FALSE;
  349. static boolean de_armor_only = FALSE;
  350. static boolean strip_sig_flag = FALSE;
  351. boolean clear_signatures = FALSE;
  352. boolean strip_spaces;
  353. static boolean c_flag = FALSE;
  354. boolean encrypt_to_self = FALSE; /* should I encrypt messages to myself? */
  355. boolean batchmode = FALSE;    /* if TRUE: don't ask questions */
  356. boolean quietmode = FALSE;
  357. boolean force_flag = FALSE;    /* overwrite existing file without asking */
  358. boolean pkcs_compat = 1;
  359. #ifdef VMS    /* kludge for those stupid VMS variable-length text records */
  360. char literal_mode = MODE_TEXT;    /* MODE_TEXT or MODE_BINARY for literal packet */
  361. #else    /* not VMS */
  362. char literal_mode = MODE_BINARY;    /* MODE_TEXT or MODE_BINARY for literal packet */
  363. #endif    /* not VMS */
  364. /* my_name is substring of default userid for secret key to make signatures */
  365. char my_name[256] = "\0"; /* null my_name means take first userid in ring */
  366. boolean keepctx = FALSE;    /* TRUE means keep .ctx file on decrypt */
  367. /* Ask for each key separately if it should be added to the keyring */
  368. boolean interactive_add = FALSE;
  369. boolean compress_enabled = TRUE;    /* attempt compression before encryption */
  370. long timeshift = 0L;    /* seconds from GMT timezone */
  371. static boolean attempt_compression; /* attempt compression before encryption */
  372. static char *outputfile = NULL;
  373. static int errorLvl = EXIT_OK;
  374. static char mcguffin[256]; /* userid search tag */
  375. boolean signature_checked = FALSE;
  376. char plainfile[MAX_PATH];
  377. int myArgc = 2;
  378. char **myArgv;
  379. struct hashedpw *passwds = 0, *keypasswds = 0;
  380. static struct hashedpw **passwdstail = &passwds;
  381.  
  382. int main(int argc, char *argv[])
  383. {
  384.     int status, opt;
  385.     char *inputfile = NULL;
  386.      char **recipient = NULL;
  387.     char **mcguffins;
  388.     char *workfile, *tempf;
  389.     boolean nestflag = FALSE;
  390.     boolean decrypt_mode = FALSE;
  391.     boolean wipeflag = FALSE;
  392.     boolean armor_flag = FALSE;        /* -a option */
  393.     boolean separate_signature = FALSE;
  394.     boolean keyflag = FALSE;
  395.     boolean encrypt_flag = FALSE;
  396.     boolean conventional_flag = FALSE;
  397.     char *clearfile = NULL;
  398.     char *literal_file = NULL;
  399.     char literal_file_name[MAX_PATH];
  400.     char cipherfile[MAX_PATH];
  401.     char keychar = '\0';
  402.     char *p;
  403.     byte ctb;
  404.     struct hashedpw *hpw;
  405.  
  406.     /* Initial messages to stderr */
  407.     pgpout = stderr;
  408.  
  409. #ifdef    DEBUG1
  410.     verbose = TRUE;
  411. #endif
  412.     /* The various places one can get passwords from.
  413.      * We accumulate them all into two lists.  One is
  414.      * to try on keys only, and is stored in no particular
  415.      * order, while the other is of unknown purpose so
  416.      * far (they may be used for conventional encryption
  417.      * or decryption as well), and are kept in a specific
  418.      * order.  If any password in the general list is found
  419.      * to decode a key, it is moved to the key list.
  420.      * The general list is not grown after initialization,
  421.      * so the tail pointer is not used after this.
  422.      */
  423.  
  424.     if ((p = getenv("PGPPASS")) != NULL)
  425.     {    hpw = xmalloc(sizeof(struct hashedpw));
  426.         hashpass(p, strlen(p), hpw->hash);
  427.         /* Add to linked list of key passwords */
  428.         hpw->next = keypasswds;
  429.         keypasswds = hpw;
  430.     }
  431.  
  432.     /* The -z "password" option should be used instead of PGPPASS if
  433.      * the environment can be displayed with the ps command (eg. BSD).
  434.      * If the system does not allow overwriting of the command line
  435.      * argument list but if it has a "hidden" environment, PGPPASS
  436.      * should be used.
  437.      */
  438.     for (opt = 1; opt < argc; ++opt)
  439.     {    p = argv[opt];
  440.         if (p[0] != '-' || p[1] != 'z')
  441.             continue;
  442.         /* Accept either "-zpassword" or "-z password" */
  443.         p += 2;
  444.         if (!*p)
  445.             p = argv[++opt];
  446.         /* p now points to password */
  447.         hpw = xmalloc(sizeof(struct hashedpw));
  448.         hashpass(p, strlen(p), hpw->hash);
  449.         /* Wipe password */
  450.         while (*p)
  451.             *p++ = ' ';
  452.         /* Add to tail of linked list of passwords */
  453.         hpw->next = 0;
  454.         *passwdstail = hpw;
  455.         passwdstail = &hpw->next;
  456.     }
  457.     /*
  458.      * If PGPPASSFD is set in the environment try to read the password
  459.      * from this file descriptor.  If you set PGPPASSFD to 0 pgp will
  460.      * use the first line read from stdin as password.
  461.      */
  462.     if ((p = getenv("PGPPASSFD")) != NULL)
  463.     {
  464.         int passfd;
  465.         if (*p && (passfd = atoi(p)) >= 0)
  466.         {
  467.             char pwbuf[256];
  468.             p = pwbuf;
  469.             while (read(passfd, p, 1) == 1 && *p != '\n')
  470.                 ++p;
  471.             hpw = xmalloc(sizeof(struct hashedpw));
  472.             hashpass(pwbuf, p-pwbuf, hpw->hash);
  473.             memset(pwbuf, 0, p-pwbuf);
  474.             /* Add to tail of linked list of passwords */
  475.             hpw->next = 0;
  476.             *passwdstail = hpw;
  477.             passwdstail = &hpw->next;
  478.         }
  479.     }
  480.  
  481.     /* Process the config file first.  Any command-line arguments will
  482.        override the config file settings */
  483.     buildfilename( mcguffin, CONFIG_FILENAME );
  484.     if ( processConfigFile( mcguffin ) < 0 )
  485.         exit(BAD_ARG_ERROR);
  486.     init_charset();
  487.  
  488. #ifdef MSDOS    /* only on MSDOS systems */
  489.     if ((p = getenv("TZ")) == NULL || *p == '\0')
  490.     {    fprintf(pgpout,PSTR("\007WARNING: Environmental variable TZ is not defined, so GMT timestamps\n\
  491. may be wrong.  See the PGP User's Guide to properly define TZ\n\
  492. in AUTOEXEC.BAT file.\n"));
  493.     }
  494. #endif    /* MSDOS */
  495.  
  496. #ifdef VMS
  497. #define TEMP "SYS$SCRATCH"
  498. #else
  499. #define TEMP "TMP"
  500. #endif /* VMS */
  501.     if ((p = getenv(TEMP)) != NULL && *p != '\0')
  502.         settmpdir(p);
  503.  
  504.     if ((myArgv = (char **) malloc((argc + 2) * sizeof(char **))) == NULL) {
  505.         fprintf(stderr, PSTR("\n\007Out of memory.\n"));
  506.         exitPGP(7);
  507.     }
  508.     myArgv[0] = NULL;
  509.     myArgv[1] = NULL;
  510.  
  511.       /* Process all the command-line option switches: */
  512.      while (optind < argc)
  513.      {    /*
  514.           * Allow random order of options and arguments (like GNU getopt)
  515.           * NOTE: this does not work with GNU getopt, use getopt.c from
  516.           * the PGP distribution.
  517.           */
  518.          if ((opt = getopt(argc, argv, OPTIONS)) == EOF)
  519.          {    if (optind == argc)        /* -- at end */
  520.                  break;
  521.              myArgv[myArgc++] = argv[optind++];
  522.              continue;
  523.          }
  524.         opt = to_lower(opt);
  525.         if (keyflag && (keychar == '\0' || (keychar == 'v' && opt == 'v')))
  526.         {
  527.             if (keychar == 'v')
  528.                 keychar = 'V';
  529.             else
  530.                 keychar = opt;
  531.             continue;
  532.         }
  533.         switch (opt)
  534.         {
  535.             case 'a': armor_flag = TRUE; emit_radix_64 = 1; break;
  536.             case 'b': separate_signature = strip_sig_flag = TRUE; break;
  537.             case 'c': encrypt_flag = conventional_flag = TRUE;
  538.                       c_flag = TRUE; break;
  539.             case 'd': decrypt_only_flag = TRUE; break;
  540.             case 'e': encrypt_flag = TRUE; break;
  541.             case 'f': filter_mode = TRUE; break;
  542.             case '?':
  543.             case 'h': usage(); break;
  544. #ifdef VMS
  545.             case 'i': literal_mode = MODE_LOCAL; break;
  546. #endif /* VMS */
  547.             case 'k': keyflag = TRUE; break;
  548.             case 'l': verbose = TRUE; break;
  549.             case 'm': moreflag = TRUE; break;
  550.             case 'p': preserve_filename = TRUE; break;
  551.             case 'o': outputfile = optarg; break;
  552.             case 's': sign_flag = TRUE; break;
  553.             case 't': literal_mode = MODE_TEXT; break;
  554.             case 'u': strncpy(my_name, optarg, sizeof(my_name)-1);
  555.                   CONVERT_TO_CANONICAL_CHARSET(my_name);
  556.                   break;
  557.             case 'w': wipeflag = TRUE; break;
  558.             case 'z': break;
  559.             /* '+' special option: does not require - */
  560.             case '+':
  561.                 if (processConfigLine(optarg) == 0)
  562.                     break;
  563.                 fprintf(stderr, "\n");
  564.                 /* fallthrough */
  565.             default:
  566.                 arg_error();
  567.         }
  568.     }
  569.     myArgv[myArgc] = NULL;    /* Just to make it NULL terminated */
  570.  
  571.     if (keyflag && keychar == '\0')
  572.         key_usage();
  573.  
  574.     signon_msg();
  575.     check_expiration_date();    /* hobble any experimental version */
  576.  
  577.     if (!filter_mode && (outputfile == NULL || strcmp(outputfile, "-")))
  578.         pgpout = stdout;
  579.  
  580. #if defined(UNIX) || defined(VMS)
  581.     umask(077); /* Make files default to private */
  582. #endif
  583.  
  584.     initsigs();
  585.  
  586.     if (keyflag)
  587.     {    status = do_keyopt(keychar);
  588.         if (status < 0)
  589.             user_error();
  590.         exitPGP(status);
  591.     }
  592.  
  593.     /* -db means break off signature certificate into separate file */
  594.     if (decrypt_only_flag && strip_sig_flag)
  595.         decrypt_only_flag = FALSE;
  596.  
  597.     if (decrypt_only_flag && armor_flag)
  598.         decrypt_mode = de_armor_only = TRUE;
  599.  
  600.     if (outputfile != NULL)
  601.         preserve_filename = FALSE;
  602.  
  603.     if (!sign_flag && !encrypt_flag && !conventional_flag && !armor_flag)
  604.     {    if (wipeflag)    /* wipe only */
  605.         {    if (myArgc != 3)
  606.                 arg_error();    /* need one argument */
  607.             if (wipefile(myArgv[2]) == 0 && remove(myArgv[2]) == 0)
  608.             {    fprintf(pgpout,PSTR("\nFile %s wiped and deleted. "),myArgv[2]);
  609.                 fprintf(pgpout, "\n");
  610.                 exitPGP(EXIT_OK);
  611.             }
  612.             exitPGP(UNKNOWN_FILE_ERROR);
  613.         }
  614.         /* decrypt if none of the -s -e -c -a -w options are specified */
  615.         decrypt_mode = TRUE;
  616.     }
  617.  
  618.      if (myArgc == 2)        /* no arguments */
  619.     {
  620. #ifdef UNIX
  621.         if (!filter_mode && !isatty(fileno(stdin)))
  622.         {    /* piping to pgp without arguments and no -f:
  623.              * switch to filter mode but don't write output to stdout
  624.              * if it's a tty, use the preserved filename */
  625.             if (!moreflag)
  626.                 pgpout = stderr;
  627.             filter_mode = TRUE;
  628.             if (isatty(fileno(stdout)) && !moreflag)
  629.                 preserve_filename = TRUE;
  630.         }
  631. #endif
  632.         if (!filter_mode)
  633.         {
  634.             if (quietmode)
  635.             {
  636.                 quietmode = FALSE;
  637.                 signon_msg();
  638.             }
  639.             fprintf(pgpout,PSTR("\nFor details on licensing and distribution, see the PGP User's Guide.\
  640. \nFor other cryptography products and custom development services, contact:\
  641. \nPhilip Zimmermann, 3021 11th St, Boulder CO 80304 USA, phone (303)541-0140\n"));
  642.             if (strcmp((p = PSTR("@translator@")), "@translator@"))
  643.                 fprintf(pgpout, p);
  644.             fprintf(pgpout,PSTR("\nFor a usage summary, type:  pgp -h\n"));
  645.             exit(BAD_ARG_ERROR);        /* error exit */
  646.         }
  647.     }
  648.     else
  649.      {    if (filter_mode)
  650.              recipient = &myArgv[2];
  651.          else
  652.          {    inputfile = myArgv[2];
  653.              recipient = &myArgv[3];
  654.          }
  655.      }
  656.  
  657.  
  658.     if (filter_mode)
  659.         inputfile = "stdin";
  660.     else
  661.     {    if (decrypt_mode && no_extension(inputfile))
  662.         {    strcpy(cipherfile, inputfile);
  663.             force_extension( cipherfile, ASC_EXTENSION );
  664.             if (file_exists (cipherfile))
  665.                 inputfile = cipherfile;
  666.             else
  667.             {    force_extension( cipherfile, PGP_EXTENSION );
  668.                 if (file_exists (cipherfile))
  669.                     inputfile = cipherfile;
  670.                 else
  671.                 {    force_extension( cipherfile, SIG_EXTENSION );
  672.                     if (file_exists (cipherfile))
  673.                         inputfile = cipherfile;
  674.                 }
  675.             }
  676.         }
  677.         if (! file_exists( inputfile ))
  678.         {    fprintf(pgpout, PSTR("\007File [%s] does not exist.\n"), inputfile);
  679.             errorLvl = FILE_NOT_FOUND_ERROR;
  680.             user_error();
  681.         }
  682.     }
  683.  
  684.     if (strlen(inputfile) >= (unsigned) MAX_PATH-4)
  685.     {    fprintf(pgpout, PSTR("\007Invalid filename: [%s] too long\n"), inputfile );
  686.         errorLvl = INVALID_FILE_ERROR;
  687.         user_error();
  688.     }
  689.     strcpy(plainfile, inputfile);
  690.  
  691.     if (filter_mode)
  692.         setoutdir(NULL);    /* NULL means use tmpdir */
  693.     else
  694.     {    if (outputfile)
  695.             setoutdir(outputfile);
  696.         else
  697.             setoutdir(inputfile);
  698.     }
  699.  
  700.     if (filter_mode)
  701.     {    workfile = tempfile(TMP_WIPE|TMP_TMPDIR);
  702.         readPhantomInput(workfile);
  703.     }
  704.     else
  705.         workfile = inputfile;
  706.  
  707.     get_header_info_from_file( workfile, &ctb, 1 );
  708.     if (decrypt_mode)
  709.     {    if (!outputfile && myArgc > 3)
  710.             outputfile = myArgv[3];
  711.         strip_spaces = FALSE;
  712.         if (!is_ctb(ctb) && is_armor_file(workfile, 0L))
  713.             do_armorfile(workfile);
  714.         else
  715.             if (do_decrypt(workfile) < 0)
  716.                 user_error();
  717.         if (batchmode && !signature_checked)
  718.             exitPGP(1);    /* alternate success, file did not have sig. */
  719.         else
  720.             exitPGP(EXIT_OK);
  721.     }
  722.  
  723.  
  724.     /*    See if plaintext input file was actually created by PGP earlier--
  725.         If it was, maybe we should NOT encapsulate it in a literal packet.
  726.         Otherwise, always encapsulate it.
  727.     */
  728.     if (force_flag)    /* for use with batchmode, force nesting */
  729.         nestflag = legal_ctb(ctb);
  730.     else
  731.         nestflag = FALSE;    /* First assume we will encapsulate it. */
  732.     if (!batchmode && !filter_mode && legal_ctb(ctb))
  733.     {    /*    Special case--may be a PGP-created packet, so
  734.             do we inhibit encapsulation in literal packet? */
  735.         fprintf(pgpout, PSTR("\n\007Input file '%s' looks like it may have been created by PGP. "),
  736.             inputfile );
  737.         fprintf(pgpout, PSTR("\nIs it safe to assume that it was created by PGP (y/N)? "));
  738.         nestflag = getyesno('n');
  739.     }    /* Possible ciphertext input file */
  740.  
  741.     if (moreflag)        /* special name to cause printout on decrypt */
  742.     {    strcpy (literal_file_name, CONSOLE_FILENAME);
  743.         literal_mode = MODE_TEXT;    /* will check for text file later */
  744.     }
  745.     else
  746.     {    strcpy (literal_file_name, inputfile);
  747. #ifdef MSDOS
  748.         strlwr (literal_file_name);
  749. #endif
  750.     }
  751.     literal_file = literal_file_name;
  752.  
  753.     /*    Make sure non-text files are not accidentally converted 
  754.         to canonical text.  This precaution should only be followed 
  755.         for US ASCII text files, since European text files may have 
  756.         8-bit character codes and still be legitimate text files 
  757.         suitable for conversion to canonical (CR/LF-terminated) 
  758.         text format. */
  759.     if (literal_mode==MODE_TEXT && !is_text_file(workfile))
  760.     {    fprintf(pgpout, 
  761. PSTR("\n\007Warning: '%s' is not a pure text file.\nFile will be treated as binary data.\n"), 
  762.             workfile);
  763.         literal_mode = MODE_BINARY; /* now expect straight binary */
  764.     }
  765.  
  766.     if (moreflag && literal_mode==MODE_BINARY)    /* For eyes only?  Can't display binary file. */
  767.     {    fprintf(pgpout, 
  768.         PSTR("\n\007Error: Only text files may be sent as display-only.\n"));
  769.         errorLvl = INVALID_FILE_ERROR;
  770.         user_error();
  771.     }        
  772.  
  773.  
  774.     /*    See if plainfile looks like it might be incompressible, 
  775.         by examining its contents for compression headers for 
  776.         commonly-used compressed file formats like PKZIP, etc.
  777.         Remember this information for later, when we are deciding
  778.         whether to attempt compression before encryption.
  779.     */
  780.     attempt_compression = compress_enabled && file_compressible(plainfile);
  781.  
  782.  
  783.     if (sign_flag)
  784.     {
  785.         if (!filter_mode && !quietmode)
  786.             fprintf(pgpout, PSTR("\nA secret key is required to make a signature. "));
  787.         if (!quietmode && my_name[0] == '\0')
  788.         {
  789.             fprintf(pgpout, PSTR("\nYou specified no user ID to select your secret key,\n\
  790. so the default user ID and key will be the most recently\n\
  791. added key on your secret keyring.\n"));
  792.         }
  793.  
  794.         strip_spaces = FALSE;
  795.         clearfile = NULL;
  796.         if (literal_mode==MODE_TEXT)
  797.         {        /* Text mode requires becoming canonical */
  798.             tempf = tempfile(TMP_WIPE|TMP_TMPDIR);
  799.             /* +clear means output file with signature in the clear,
  800.                only in combination with -t and -a, not with -e or -b */
  801.             if (!encrypt_flag && !separate_signature &&
  802.                     emit_radix_64 && clear_signatures) {
  803.                 clearfile = workfile;
  804.                 strip_spaces = TRUE;
  805.             }
  806.             make_canonical( workfile, tempf );
  807.             if (!clearfile)
  808.                 rmtemp(workfile);
  809.             workfile = tempf;
  810.         }
  811.         if ((emit_radix_64 || encrypt_flag) && !separate_signature)
  812.             tempf = tempfile(TMP_WIPE|TMP_TMPDIR);
  813.         else
  814.             tempf = tempfile(TMP_WIPE);
  815.         /* for clear signatures we create a separate signature */
  816.         status = signfile(nestflag, separate_signature || (clearfile != NULL),
  817.                             my_name, workfile, tempf, literal_mode, literal_file );
  818.         rmtemp(workfile);
  819.         workfile = tempf;
  820.  
  821.         if (status < 0) /* signfile failed */
  822.         {    fprintf(pgpout, PSTR("\007Signature error\n") );
  823.             errorLvl = SIGNATURE_ERROR;
  824.             user_error();
  825.         }
  826.  
  827.         /*  We used to compress signed files only if they were also armored.
  828.             Now that we have clear signatures it makes more sense to always
  829.             compress signature files. */
  830.         if (attempt_compression && !separate_signature && !encrypt_flag &&
  831.                 !clearfile)
  832.         {    tempf = tempfile(TMP_WIPE|TMP_TMPDIR);
  833.             squish_file(workfile, tempf);
  834.             rmtemp(workfile);
  835.             workfile = tempf;
  836.         }
  837.  
  838.     }    /* sign file */
  839.     else if (!nestflag)
  840.     {    /*    Prepend CTB_LITERAL byte to plaintext file.
  841.             --sure wish this pass could be optimized away. */
  842.         tempf = tempfile(TMP_WIPE);
  843.         status = make_literal( workfile, tempf, literal_mode, literal_file );
  844.         rmtemp(workfile);
  845.         workfile = tempf;
  846.     }
  847.  
  848.     if (encrypt_flag)
  849.     {
  850.         tempf = tempfile(TMP_WIPE);
  851.         if (!conventional_flag)
  852.         {
  853.             if (!filter_mode && !quietmode)
  854.                 fprintf(pgpout, PSTR("\n\nRecipients' public key(s) will be used to encrypt. "));
  855.              if (recipient == NULL || *recipient == NULL || **recipient == '\0')
  856.             {    /* no recipient specified on command line */
  857.                 fprintf(pgpout, PSTR("\nA user ID is required to select the recipient's public key. "));
  858.                 fprintf(pgpout, PSTR("\nEnter the recipient's user ID: "));
  859.                 getstring( mcguffin, 255, TRUE );    /* echo keyboard */
  860.                 if ((mcguffins = (char **) malloc (2 * sizeof(char *))) == NULL) {
  861.                     fprintf(stderr, PSTR("\n\007Out of memory.\n"));
  862.                     exitPGP(7);
  863.                 }
  864.                 mcguffins[0] = mcguffin;
  865.                 mcguffins[1] = "";
  866.             }
  867.             else
  868.             {    /* recipient specified on command line */
  869.                 mcguffins = recipient;
  870.             }
  871.             for (recipient = mcguffins; *recipient != NULL && 
  872.                  **recipient != '\0'; recipient++) {
  873.                 CONVERT_TO_CANONICAL_CHARSET(*recipient);
  874.             }
  875.             status = encryptfile( mcguffins, workfile, tempf, attempt_compression);
  876.         }
  877.         else
  878.             status = idea_encryptfile( workfile, tempf, attempt_compression);
  879.  
  880.         rmtemp(workfile);
  881.         workfile = tempf;
  882.  
  883.         if (status < 0)
  884.         {    fprintf(pgpout, PSTR("\007Encryption error\n") );
  885.             errorLvl = (conventional_flag ? ENCR_ERROR : RSA_ENCR_ERROR);
  886.             user_error();
  887.         }
  888.     }    /* encrypt file */
  889.  
  890.     if (outputfile)        /* explicit output file overrides filter mode */
  891.         filter_mode = (strcmp(outputfile, "-") == 0);
  892.  
  893.     if (filter_mode)
  894.     {    if (emit_radix_64)
  895.         {    /* NULL for outputfile means write to stdout */
  896.             if (armor_file(workfile, NULL, inputfile, clearfile) != 0)
  897.             {    errorLvl = UNKNOWN_FILE_ERROR;
  898.                 user_error();
  899.             }
  900.             if (clearfile)
  901.                 rmtemp(clearfile);
  902.         }
  903.         else
  904.             if (writePhantomOutput(workfile) < 0)
  905.             {    errorLvl = UNKNOWN_FILE_ERROR;
  906.                 user_error();
  907.             }
  908.         rmtemp(workfile);
  909.     }
  910.     else
  911.     {    char name[MAX_PATH];
  912.         if (outputfile)
  913.             strcpy(name, outputfile);
  914.         else
  915.         {    strcpy(name, inputfile);
  916.             drop_extension(name);
  917.         }
  918.         if (no_extension(name))
  919.         {    if (emit_radix_64)
  920.                 force_extension(name, ASC_EXTENSION);
  921.             else if (sign_flag && separate_signature)
  922.                 force_extension(name, SIG_EXTENSION);
  923.             else
  924.                 force_extension(name, PGP_EXTENSION);
  925.         }
  926.         if (emit_radix_64)
  927.         {
  928.             if (armor_file(workfile, name, inputfile, clearfile) != 0)
  929.             {    errorLvl = UNKNOWN_FILE_ERROR;
  930.                 user_error();
  931.             }
  932.             if (clearfile)
  933.                 rmtemp(clearfile);
  934.         }
  935.         else
  936.         {    if ((outputfile = savetemp(workfile, name)) == NULL)
  937.             {    errorLvl = UNKNOWN_FILE_ERROR;
  938.                 user_error();
  939.             }
  940.             if (!quietmode)
  941.             {
  942.                 if (encrypt_flag)
  943.                     fprintf(pgpout, PSTR("\nCiphertext file: %s\n"), outputfile);
  944.                 else if (sign_flag)
  945.                     fprintf(pgpout, PSTR("\nSignature file: %s\n"), outputfile);
  946.             }
  947.         }
  948.     }
  949.  
  950.     if (wipeflag)
  951.     {    /* destroy every trace of plaintext */
  952.         if (wipefile(inputfile) == 0)
  953.         {    remove(inputfile);
  954.             fprintf(pgpout,PSTR("\nFile %s wiped and deleted. "),inputfile);
  955.             fprintf(pgpout, "\n");
  956.         }
  957.     }
  958.  
  959.     exitPGP(EXIT_OK);
  960.     return(0);    /* to shut up lint and some compilers */
  961. }    /* main */
  962.  
  963. #ifdef MSDOS
  964. #include <dos.h>
  965. static char *dos_errlst[] = {
  966.     "Write protect error",        /* PSTR ("Write protect error") */
  967.     "Unknown unit",
  968.     "Drive not ready",            /* PSTR ("Drive not ready") */
  969.     "3", "4", "5", "6", "7", "8", "9",
  970.     "Write error",                /* PSTR ("Write error") */
  971.     "Read error",                /* PSTR ("Read error") */
  972.     "General failure",
  973. };
  974.  
  975. /* handler for msdos 'harderrors' */
  976. #ifndef OS2
  977. #ifdef __TURBOC__    /* Turbo C 2.0 */
  978. static int dostrap(int errval)
  979. #else
  980. static void dostrap(unsigned deverr, unsigned errval)
  981. #endif
  982. {
  983.     char errbuf[64];
  984.     int i;
  985.     sprintf(errbuf, "\r\nDOS error: %s\r\n", dos_errlst[errval]);
  986.     i = 0;
  987.     do
  988.         bdos(2,(unsigned int)errbuf[i],0);
  989.     while (errbuf[++i]);
  990. #ifdef __TURBOC__
  991.     return 0;    /* ignore (fopen will return NULL) */
  992. #else
  993.     return;
  994. #endif
  995. }
  996. #endif /* MSDOS */
  997. #endif
  998.  
  999. static void initsigs()
  1000. {
  1001. #ifdef MSDOS
  1002. #ifndef OS2
  1003. #ifdef __TURBOC__
  1004.     harderr(dostrap);
  1005. #else /* MSC */
  1006. #ifndef __GNUC__ /* DJGPP's not MSC */
  1007.     _harderr(dostrap);
  1008. #endif
  1009. #endif
  1010. #endif
  1011. #endif /* MSDOS */
  1012. #ifdef SIGINT
  1013. #ifdef ATARI
  1014.     signal(SIGINT,(sigfunc_t) breakHandler);
  1015. #else
  1016.     if (signal(SIGINT, SIG_IGN) != SIG_IGN)
  1017.         signal(SIGINT,breakHandler);
  1018. #if defined(UNIX) || defined(VMS)
  1019.     if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
  1020.         signal(SIGHUP,breakHandler);
  1021.     if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
  1022.         signal(SIGQUIT,breakHandler);
  1023. #ifdef UNIX
  1024.     signal(SIGPIPE,breakHandler);
  1025. #endif
  1026.     signal(SIGTERM,breakHandler);
  1027. #ifndef DEBUG
  1028.     signal(SIGTRAP,breakHandler);
  1029.     signal(SIGSEGV,breakHandler);
  1030.     signal(SIGILL,breakHandler);
  1031. #ifdef SIGBUS
  1032.     signal(SIGBUS,breakHandler);
  1033. #endif
  1034. #endif /* DEBUG */
  1035. #endif /* UNIX */
  1036. #endif /* not Atari */
  1037. #endif /* SIGINT */
  1038. }    /* initsigs */
  1039.  
  1040.  
  1041. static void do_armorfile(char *armorfile)
  1042. {
  1043.     char *tempf;
  1044.     char cipherfile[MAX_PATH];
  1045.     long linepos = 0;
  1046.     int status;
  1047.     int success = 0;
  1048.  
  1049.     while (TRUE)
  1050.     {    /* Handle transport armor stripping */
  1051.         tempf = tempfile(0);
  1052.         strip_spaces = FALSE;    /* de_armor_file() sets this for clear signature files */
  1053.         status = de_armor_file(armorfile,tempf,&linepos);
  1054.         if (status)
  1055.         {    fprintf(pgpout,PSTR("\n\007Error: Transport armor stripping failed for file %s\n"),armorfile);
  1056.             errorLvl = INVALID_FILE_ERROR;
  1057.             user_error();     /* Bad file */
  1058.         }
  1059.         if (keepctx || de_armor_only)
  1060.         {    if (outputfile && de_armor_only)
  1061.             {    if (strcmp(outputfile, "-") == 0)
  1062.                 {    writePhantomOutput(tempf);
  1063.                     rmtemp(tempf);
  1064.                     return;
  1065.                 }
  1066.                 strcpy(cipherfile, outputfile);
  1067.             }
  1068.             else
  1069.             {    strcpy(cipherfile, file_tail(armorfile));
  1070.                 force_extension(cipherfile, PGP_EXTENSION);
  1071.             }
  1072.             if ((tempf = savetemp(tempf, cipherfile)) == NULL)
  1073.             {    errorLvl = UNKNOWN_FILE_ERROR;
  1074.                 user_error();
  1075.             }
  1076.             if (!quietmode)
  1077.                 fprintf(pgpout,PSTR("Stripped transport armor from '%s', producing '%s'.\n"),
  1078.                     armorfile, tempf);
  1079.             /* -da flag: don't decrypt */
  1080.             if (de_armor_only || do_decrypt(tempf) >= 0)
  1081.                 ++success;
  1082.         }
  1083.         else
  1084.         {    if (do_decrypt(tempf) >= 0)
  1085.                 ++success;
  1086.             rmtemp(tempf);
  1087.         }
  1088.  
  1089.         if (!is_armor_file(armorfile, linepos))
  1090.         {
  1091.             if (!success)    /* print error msg if we didn't decrypt anything */
  1092.                 user_error();
  1093.             return;
  1094.         }
  1095.  
  1096.         fprintf (pgpout, PSTR("\nLooking for next packet in '%s'...\n"), armorfile);
  1097.     }
  1098. }    /* do_armorfile */
  1099.  
  1100.  
  1101. static int do_decrypt(char *cipherfile)
  1102. {
  1103.     char *outfile = NULL;
  1104.     int status, i;
  1105.     boolean nested_info = FALSE;
  1106.     char ringfile[MAX_PATH];
  1107.     byte ctb;
  1108.     byte header[8]; /* used to classify file type at the end. */
  1109.     char preserved_name[MAX_PATH];
  1110.     char *newname;
  1111.  
  1112.     /* will be set to the original file name after processing a literal packet */
  1113.     preserved_name[0] = '\0';
  1114.  
  1115.     do    /* while nested parsable info present */
  1116.     {
  1117.         if (nested_info)
  1118.         {    rmtemp(cipherfile);        /* never executed on first pass */
  1119.             cipherfile = outfile;
  1120.         }
  1121.         if (get_header_info_from_file( cipherfile, &ctb, 1) < 0)
  1122.         {    fprintf(pgpout,PSTR("\n\007Can't open ciphertext file '%s'\n"),cipherfile);
  1123.             errorLvl = FILE_NOT_FOUND_ERROR;
  1124.             return -1;
  1125.         }
  1126.  
  1127.         if (!is_ctb(ctb))        /* not a real CTB -- complain */
  1128.             break;
  1129.  
  1130.         outfile = tempfile(TMP_WIPE);
  1131.  
  1132.         /* PKE is Public Key Encryption */
  1133.         if (is_ctb_type( ctb, CTB_PKE_TYPE ))
  1134.         {
  1135.             if (!quietmode)
  1136.                 fprintf(pgpout,PSTR("\nFile is encrypted.  Secret key is required to read it. "));
  1137.  
  1138.             /* Decrypt to scratch file since we may have a LITERAL2 */
  1139.             status = decryptfile( cipherfile, outfile );
  1140.  
  1141.             if (status < 0) /* error return */
  1142.             {    errorLvl = RSA_DECR_ERROR;
  1143.                 return -1;
  1144.             }
  1145.             nested_info = (status > 0);
  1146.         }        /* outer CTB is PKE type */
  1147.  
  1148.         if (is_ctb_type( ctb, CTB_SKE_TYPE ))
  1149.         {
  1150.             if (decrypt_only_flag)
  1151.             {    /* swap file names instead of just copying the file */
  1152.                 rmtemp(outfile);
  1153.                 outfile = cipherfile;
  1154.                 cipherfile = NULL;
  1155.                 if (!quietmode)
  1156.                     fprintf(pgpout,PSTR("\nThis file has a signature, which will be left in place.\n"));
  1157.                 break;    /* Do no more */
  1158.             }
  1159.             if (!quietmode)
  1160.                 fprintf(pgpout,PSTR("\nFile has signature.  Public key is required to check signature. "));
  1161.  
  1162.             status = check_signaturefile( cipherfile, outfile, strip_sig_flag, preserved_name );
  1163.  
  1164.             if (status < 0) /* error return */
  1165.             {    errorLvl = SIGNATURE_CHECK_ERROR;
  1166.                 return -1;
  1167.             }
  1168.             nested_info = (status > 0);
  1169.  
  1170.             if (strcmp(preserved_name, "/dev/null") == 0)
  1171.             {    rmtemp(outfile);
  1172.                 fprintf(pgpout, "\n");
  1173.                 return 0;
  1174.             }
  1175.         }        /* outer CTB is SKE type */
  1176.  
  1177.  
  1178.         if (is_ctb_type( ctb, CTB_CKE_TYPE ))
  1179.         {        /* Conventional Key Encrypted ciphertext. */
  1180.             /* Tell user it's encrypted here, and prompt for password in subroutine. */
  1181.             if (!quietmode)
  1182.                 fprintf(pgpout,PSTR("\nFile is conventionally encrypted.  "));
  1183.             /* Decrypt to scratch file since it may be a LITERAL2 */
  1184.             status = idea_decryptfile( cipherfile, outfile );
  1185.             if (status < 0) /* error return */
  1186.             {    errorLvl = DECR_ERROR;
  1187.                 return -1;    /* error exit status */
  1188.             }
  1189.             nested_info = (status > 0);
  1190.         }        /* CTB is CKE type */
  1191.  
  1192.  
  1193.         if (is_ctb_type( ctb, CTB_COMPRESSED_TYPE ))
  1194.         {        /* Compressed text. */
  1195.             status = decompress_file( cipherfile, outfile );
  1196.             if (status < 0) /* error return */
  1197.             {    errorLvl = DECOMPRESS_ERROR;
  1198.                 return -1;
  1199.             }
  1200.             /* Always assume nested information... */
  1201.             nested_info = TRUE;
  1202.         }        /* CTB is COMPRESSED type */
  1203.  
  1204.  
  1205.         if (is_ctb_type( ctb, CTB_LITERAL_TYPE ) || is_ctb_type( ctb, CTB_LITERAL2_TYPE))
  1206.         {        /* Raw plaintext.  Just copy it.  No more nesting. */
  1207.             /* Strip off CTB_LITERAL prefix byte from file: */
  1208.             /* strip_literal may alter plainfile; will set mode */
  1209.             status = strip_literal( cipherfile, outfile,
  1210.                     preserved_name, &literal_mode);
  1211.             if (status < 0) /* error return */
  1212.             {    errorLvl = UNKNOWN_FILE_ERROR;
  1213.                 return -1;
  1214.             }
  1215.             nested_info = FALSE;
  1216.         }        /* CTB is LITERAL type */
  1217.  
  1218.  
  1219.         if ((ctb == CTB_CERT_SECKEY) || (ctb == CTB_CERT_PUBKEY))
  1220.         {    rmtemp(outfile);
  1221.             if (decrypt_only_flag)
  1222.             {    /* swap file names instead of just copying the file */
  1223.                 outfile = cipherfile;
  1224.                 cipherfile = NULL;
  1225.                 break;    /* no further processing */
  1226.             }
  1227.                 /* Key ring.  View it. */
  1228.             fprintf(pgpout, PSTR("\nFile contains key(s).  Contents follow...") );
  1229.             if (view_keyring( NULL, cipherfile, TRUE, FALSE ) < 0)
  1230.             {    errorLvl = KEYRING_VIEW_ERROR;
  1231.                 return -1;
  1232.             }
  1233.             /* filter mode explicit requested with -f */
  1234.             if (filter_mode && !preserve_filename)
  1235.                 return 0; /*    No output file */
  1236.             if (batchmode)
  1237.                 return 0;
  1238.             if (ctb == CTB_CERT_SECKEY)
  1239.                 buildfilename(ringfile,SECRET_KEYRING_FILENAME);
  1240.             else
  1241.                 buildfilename(ringfile,PUBLIC_KEYRING_FILENAME);
  1242.             /*    Ask if it should be put on key ring */
  1243.             fprintf(pgpout, PSTR("\nDo you want to add this keyfile to keyring '%s' (y/N)? "), ringfile);
  1244.             if (!getyesno('n'))
  1245.                 return 0;
  1246.             status = addto_keyring(cipherfile,ringfile);
  1247.             if (status < 0)
  1248.             {    fprintf(pgpout, PSTR("\007Keyring add error. ") );
  1249.                 errorLvl = KEYRING_ADD_ERROR;
  1250.                 return -1;
  1251.             }
  1252.             return 0; /*    No output file */
  1253.         }        /* key ring.  view it. */
  1254.  
  1255.     } while (nested_info);
  1256.     /* No more nested parsable information */
  1257.  
  1258.     if (outfile == NULL)    /* file was not encrypted */
  1259.     {    if (!filter_mode && !moreflag)
  1260.         {    fprintf(pgpout,PSTR("\007\nError: '%s' is not a ciphertext, signature, or key file.\n"),
  1261.                 cipherfile);
  1262.             errorLvl = UNKNOWN_FILE_ERROR;
  1263.             return -1;
  1264.         }
  1265.         outfile = cipherfile;
  1266.     }
  1267.     else
  1268.         if (cipherfile)
  1269.             rmtemp(cipherfile);
  1270.  
  1271.     if (moreflag || (strcmp(preserved_name,CONSOLE_FILENAME) == 0))
  1272.     {    /* blort to screen */
  1273.         if (strcmp(preserved_name,CONSOLE_FILENAME) == 0)
  1274.         {    fprintf(pgpout, 
  1275.             PSTR("\n\nThis message is marked \"For your eyes only\".  Display now (Y/n)? "));
  1276.             if (batchmode || !getyesno('y'))
  1277.             {    /* no -- abort display, and clean up */
  1278.                 rmtemp(outfile);
  1279.                 return 0;
  1280.             }
  1281.         }
  1282.         if (!quietmode)
  1283.             fprintf(pgpout, PSTR("\n\nPlaintext message follows...\n"));
  1284.         else
  1285.             putc('\n', pgpout);
  1286.         fprintf(pgpout, "------------------------------\n");
  1287.         more_file(outfile);
  1288.         /* Disallow saving to disk if outfile is console-only: */
  1289.         if (strcmp(preserved_name,CONSOLE_FILENAME) == 0)
  1290.             clearscreen();    /* remove all evidence */
  1291.         else if (!quietmode && !batchmode)
  1292.         {    
  1293.             fprintf(pgpout, PSTR("Save this file permanently (y/N)? "));
  1294.             if (getyesno('n'))
  1295.             {    char moreFilename[256];
  1296.                 fprintf(pgpout,PSTR("Enter filename to save file as: "));
  1297.                 if (preserved_name[0])
  1298.                     fprintf(pgpout, "[%s]: ", file_tail(preserved_name));
  1299.                 getstring( moreFilename, 255, TRUE );
  1300.                 if (*moreFilename == '\0')
  1301.                 {    if (*preserved_name != '\0')
  1302.                         savetemp (outfile, file_tail(preserved_name));
  1303.                     else
  1304.                         rmtemp(outfile);
  1305.                 }
  1306.                 else
  1307.                     savetemp (outfile, moreFilename);
  1308.                 return 0;
  1309.             }
  1310.         }
  1311.         rmtemp(outfile);
  1312.         return 0;
  1313.     }    /* blort to screen */
  1314.  
  1315.     if (outputfile)
  1316.     {    if (!strcmp(outputfile, "/dev/null"))
  1317.         {    rmtemp(outfile);
  1318.             return 0;
  1319.         }
  1320.         filter_mode = (strcmp(outputfile, "-") == 0);
  1321.         strcpy(plainfile, outputfile);
  1322.     }
  1323.     else
  1324. #ifdef VMS
  1325.         /* VMS null extension has to be ".", not "" */
  1326.         force_extension(plainfile, ".");
  1327. #else    /* not VMS */
  1328.         drop_extension(plainfile);
  1329. #endif    /* not VMS */
  1330.  
  1331.     if (!preserve_filename && filter_mode)
  1332.     {    if (writePhantomOutput(outfile) < 0)
  1333.         {    errorLvl = UNKNOWN_FILE_ERROR;
  1334.             return -1;
  1335.         }
  1336.         rmtemp(outfile);
  1337.         return 0;
  1338.     }
  1339.  
  1340.     if (preserve_filename && preserved_name[0] != '\0')
  1341.         strcpy(plainfile, file_tail(preserved_name));
  1342.  
  1343.     if (quietmode)
  1344.     {    if (savetemp(outfile, plainfile) == NULL)
  1345.         {    errorLvl = UNKNOWN_FILE_ERROR;
  1346.             return -1;
  1347.         }
  1348.         return 0;
  1349.     }
  1350.     if (!verbose)    /* if other filename messages were suppressed */
  1351.         fprintf(pgpout,PSTR("\nPlaintext filename: %s"), plainfile);
  1352.  
  1353.  
  1354.     /*---------------------------------------------------------*/
  1355.  
  1356.     /*    One last thing-- let's attempt to classify some of the more
  1357.         frequently occurring cases of plaintext output files, as an
  1358.         aid to the user.
  1359.  
  1360.         For example, if output file is a public key, it should have
  1361.         the right extension on the filename.
  1362.  
  1363.         Also, it will likely be common to encrypt files created by
  1364.         various archivers, so they should be renamed with the archiver
  1365.         extension.
  1366.     */
  1367.     get_header_info_from_file( outfile, header, 8 );
  1368.  
  1369.     newname = NULL;
  1370.     if (header[0] == CTB_CERT_PUBKEY)
  1371.     {    /* Special case--may be public key, worth renaming */
  1372.         fprintf(pgpout, PSTR("\nPlaintext file '%s' looks like it contains a public key."),
  1373.             plainfile );
  1374.         newname = maybe_force_extension( plainfile, PGP_EXTENSION );
  1375.     }    /* Possible public key output file */
  1376.  
  1377.     else
  1378.     if ((i = compressSignature( header )) >= 0)
  1379.     {    /*    Special case--may be an archived/compressed file, worth renaming    */
  1380.         fprintf(pgpout, PSTR("\nPlaintext file '%s' looks like a %s file."),
  1381.             plainfile, compressName[i] );
  1382.         newname = maybe_force_extension( plainfile, compressExt[i] );
  1383.     }    /*    Possible archived/compressed output file    */
  1384.  
  1385.     else
  1386.     if (is_ctb(header[0]) &&
  1387.        (is_ctb_type (header[0], CTB_PKE_TYPE)
  1388.      || is_ctb_type (header[0], CTB_SKE_TYPE)
  1389.      || is_ctb_type (header[0], CTB_CKE_TYPE)))
  1390.     {    /* Special case--may be another ciphertext file, worth renaming */
  1391.         fprintf(pgpout, PSTR("\n\007Output file '%s' may contain more ciphertext or signature."),
  1392.             plainfile );
  1393.         newname = maybe_force_extension( plainfile, PGP_EXTENSION );
  1394.     }    /* Possible ciphertext output file */
  1395.  
  1396.     if (savetemp(outfile, (newname ? newname : plainfile)) == NULL)
  1397.     {    errorLvl = UNKNOWN_FILE_ERROR;
  1398.         return -1;
  1399.     }
  1400.  
  1401.     fprintf (pgpout, "\n");
  1402.     return 0;
  1403. } /* do_decrypt */
  1404.  
  1405.  
  1406. static int do_keyopt(char keychar)
  1407. {
  1408.     char keyfile[MAX_PATH];
  1409.     char ringfile[MAX_PATH];
  1410.     char *workfile;
  1411.     int status;
  1412.  
  1413.     if ((filter_mode || batchmode)
  1414.         && (keychar == 'g' || keychar == 'e' || keychar == 'd'
  1415.             || (keychar == 'r' && sign_flag)))
  1416.     {    errorLvl = NO_BATCH;
  1417.         arg_error();     /* interactive process, no go in batch mode */
  1418.     }
  1419.  
  1420.     switch (keychar)
  1421.     {
  1422.  
  1423.         /*-------------------------------------------------------*/
  1424.         case 'g':
  1425.         {    /*    Key generation
  1426.                 Arguments: bitcount, bitcount
  1427.             */
  1428.             char    keybits[6], ebits[6];
  1429.  
  1430.             if (myArgc > 2)
  1431.                 strncpy( keybits, myArgv[2], sizeof(keybits)-1 );
  1432.             else
  1433.                 keybits[0] = '\0';
  1434.  
  1435.             if (myArgc > 3)
  1436.                 strncpy( ebits, myArgv[3], sizeof(ebits)-1 );
  1437.             else
  1438.                 ebits[0] = '\0';
  1439.  
  1440.             /* dokeygen writes the keys out to the key rings... */
  1441.             status = dokeygen(keybits, ebits);
  1442.  
  1443.             if (status < 0)
  1444.             {    fprintf(pgpout, PSTR("\007Keygen error. ") );
  1445.                 errorLvl = KEYGEN_ERROR;
  1446.             }
  1447.             return status;
  1448.         }    /* Key generation */
  1449.  
  1450.         /*-------------------------------------------------------*/
  1451.         case 'c':
  1452.         {    /*    Key checking
  1453.                 Arguments: userid, ringfile
  1454.             */
  1455.  
  1456.             if (myArgc < 3)        /* Default to all user ID's */
  1457.                 mcguffin[0] = '\0';
  1458.             else
  1459.             {    strcpy ( mcguffin, myArgv[2] );
  1460.                 if (strcmp( mcguffin, "*" ) == 0)
  1461.                     mcguffin[0] = '\0';
  1462.             }
  1463.             CONVERT_TO_CANONICAL_CHARSET(mcguffin);
  1464.  
  1465.             if (myArgc < 4) /* default key ring filename */
  1466.                 buildfilename( ringfile, PUBLIC_KEYRING_FILENAME );
  1467.             else
  1468.                 strncpy( ringfile, myArgv[3], sizeof(ringfile)-1 );
  1469.  
  1470.             if ((myArgc < 4 && myArgc > 2)    /* Allow just key file as arg */
  1471.             && has_extension( myArgv[2], PGP_EXTENSION ) )
  1472.             {    strcpy( ringfile, myArgv[2] );
  1473.                 mcguffin[0] = '\0';
  1474.             }
  1475.  
  1476.             status = dokeycheck( mcguffin, ringfile, CHECK_ALL );
  1477.  
  1478.             if (status < 0)
  1479.             {    fprintf(pgpout, PSTR("\007Keyring check error. ") );
  1480.                 errorLvl = KEYRING_CHECK_ERROR;
  1481.             }
  1482.             if (status >= 0 && mcguffin[0] != '\0')
  1483.                 return status;    /* just checking a single user, dont do maintenance */
  1484.  
  1485.             if ((status = maint_check(ringfile, 0)) < 0 && status != -7)
  1486.             {    fprintf(pgpout, PSTR("\007Maintenance pass error. ") );
  1487.                 errorLvl = KEYRING_CHECK_ERROR;
  1488.             }
  1489.  
  1490.             return (status == -7 ? 0 : status);
  1491.         }    /* Key check */
  1492.  
  1493.         /*-------------------------------------------------------*/
  1494.         case 'm':
  1495.         {    /*    Maintenance pass
  1496.                 Arguments: ringfile
  1497.             */
  1498.  
  1499.             if (myArgc < 3) /* default key ring filename */
  1500.                 buildfilename( ringfile, PUBLIC_KEYRING_FILENAME );
  1501.             else
  1502.                 strcpy( ringfile, myArgv[2] );
  1503.  
  1504. #ifdef MSDOS
  1505.             strlwr( ringfile );
  1506. #endif
  1507.             if (! file_exists( ringfile ))
  1508.                 default_extension( ringfile, PGP_EXTENSION );
  1509.  
  1510.             if ((status = maint_check(ringfile,
  1511.                     MAINT_VERBOSE|(c_flag ? MAINT_CHECK : 0))) < 0)
  1512.             {    if (status == -7)
  1513.                     fprintf(pgpout, PSTR("File '%s' is not a public keyring\n"), ringfile);
  1514.                 fprintf(pgpout, PSTR("\007Maintenance pass error. ") );
  1515.                 errorLvl = KEYRING_CHECK_ERROR;
  1516.             }
  1517.             return status;
  1518.         }    /* Maintenance pass */
  1519.  
  1520.         /*-------------------------------------------------------*/
  1521.         case 's':
  1522.         {    /*    Key signing
  1523.                 Arguments: her_id, keyfile
  1524.             */
  1525.  
  1526.             if (myArgc >= 4)
  1527.                 strncpy( keyfile, myArgv[3], sizeof(keyfile)-1 );
  1528.             else
  1529.                 buildfilename( keyfile, PUBLIC_KEYRING_FILENAME );
  1530.  
  1531.             if (myArgc >= 3)
  1532.                 strcpy( mcguffin, myArgv[2] );    /* Userid to sign */
  1533.             else
  1534.             {
  1535.                 fprintf(pgpout, PSTR("\nA user ID is required to select the public key you want to sign. "));
  1536.                 if (batchmode)    /* not interactive, userid must be on command line */
  1537.                     return -1;
  1538.                 fprintf(pgpout, PSTR("\nEnter the public key's user ID: "));
  1539.                 getstring( mcguffin, 255, TRUE );    /* echo keyboard */
  1540.             }
  1541.             CONVERT_TO_CANONICAL_CHARSET(mcguffin);
  1542.  
  1543.             if (my_name[0] == '\0')
  1544.             {
  1545.                 fprintf(pgpout, PSTR("\nA secret key is required to make a signature. "));
  1546.                 fprintf(pgpout, PSTR("\nYou specified no user ID to select your secret key,\n\
  1547. so the default user ID and key will be the most recently\n\
  1548. added key on your secret keyring.\n"));
  1549.             }
  1550.  
  1551.             status = signkey ( mcguffin, my_name, keyfile );
  1552.  
  1553.             if (status >= 0) {
  1554.                 status = maint_update(keyfile);
  1555.                 if (status == -7)    /* ringfile is a keyfile or secret keyring */
  1556.                 {    fprintf(pgpout, "Warning: '%s' is not a public keyring\n", keyfile);
  1557.                     return 0;
  1558.                 }
  1559.                 if (status < 0)
  1560.                     fprintf(pgpout, PSTR("\007Maintenance pass error. ") );
  1561.             }
  1562.  
  1563.             if (status < 0)
  1564.             {    fprintf(pgpout, PSTR("\007Key signature error. ") );
  1565.                 errorLvl = KEY_SIGNATURE_ERROR;
  1566.             }
  1567.             return status;
  1568.         }    /* Key signing */
  1569.  
  1570.  
  1571.         /*-------------------------------------------------------*/
  1572.         case 'd':
  1573.         {    /*    disable/revoke key
  1574.                 Arguments: userid, keyfile
  1575.             */
  1576.  
  1577.             if (myArgc >= 4)
  1578.                 strncpy( keyfile, myArgv[3], sizeof(keyfile)-1 );
  1579.             else
  1580.                 buildfilename( keyfile, PUBLIC_KEYRING_FILENAME );
  1581.  
  1582.             if (myArgc >= 3)
  1583.                 strcpy( mcguffin, myArgv[2] );    /* Userid to sign */
  1584.             else
  1585.             {
  1586.                 fprintf(pgpout, PSTR("\nA user ID is required to select the key you want to revoke or disable. "));
  1587.                 fprintf(pgpout, PSTR("\nEnter user ID: "));
  1588.                 getstring( mcguffin, 255, TRUE );    /* echo keyboard */
  1589.             }
  1590.             CONVERT_TO_CANONICAL_CHARSET(mcguffin);
  1591.  
  1592.             status = disable_key ( mcguffin, keyfile );
  1593.  
  1594.             if (status >= 0) {
  1595.                 status = maint_update(keyfile);
  1596.                 if (status == -7)    /* ringfile is a keyfile or secret keyring */
  1597.                 {    fprintf(pgpout, "Warning: '%s' is not a public keyring\n", keyfile);
  1598.                     return 0;
  1599.                 }
  1600.                 if (status < 0)
  1601.                     fprintf(pgpout, PSTR("\007Maintenance pass error. ") );
  1602.             }
  1603.  
  1604.             if (status < 0)
  1605.                 errorLvl = KEY_SIGNATURE_ERROR;
  1606.             return status;
  1607.         }    /* Key compromise */
  1608.  
  1609.         /*-------------------------------------------------------*/
  1610.         case 'e':
  1611.         {    /*    Key editing
  1612.                 Arguments: userid, ringfile
  1613.             */
  1614.  
  1615.             if (myArgc >= 4)
  1616.                 strncpy( ringfile, myArgv[3], sizeof(ringfile)-1 );
  1617.             else    /* default key ring filename */
  1618.                 buildfilename( ringfile, PUBLIC_KEYRING_FILENAME );
  1619.  
  1620.             if (myArgc >= 3)
  1621.                 strcpy( mcguffin, myArgv[2] );    /* Userid to edit */
  1622.             else
  1623.             {
  1624.                 fprintf(pgpout, PSTR("\nA user ID is required to select the key you want to edit. "));
  1625.                 fprintf(pgpout, PSTR("\nEnter the key's user ID: "));
  1626.                 getstring( mcguffin, 255, TRUE );    /* echo keyboard */
  1627.             }
  1628.             CONVERT_TO_CANONICAL_CHARSET(mcguffin);
  1629.  
  1630.             status = dokeyedit( mcguffin, ringfile );
  1631.  
  1632.             if (status >= 0) {
  1633.                 status = maint_update(ringfile);
  1634.                 if (status == -7)
  1635.                     status = 0;    /* ignore "not a public keyring" error */
  1636.                 if (status < 0)
  1637.                     fprintf(pgpout, PSTR("\007Maintenance pass error. ") );
  1638.             }
  1639.  
  1640.             if (status < 0)
  1641.             {    fprintf(pgpout, PSTR("\007Keyring edit error. ") );
  1642.                 errorLvl = KEYRING_EDIT_ERROR;
  1643.             }
  1644.             return status;
  1645.         }    /* Key edit */
  1646.  
  1647.         /*-------------------------------------------------------*/
  1648.         case 'a':
  1649.         {    /*    Add key to key ring
  1650.                 Arguments: keyfile, ringfile
  1651.             */
  1652.  
  1653.             if (myArgc < 3 && !filter_mode)
  1654.                 arg_error();
  1655.  
  1656.             if (!filter_mode) {    /* Get the keyfile from args */
  1657.                 strncpy( keyfile, myArgv[2], sizeof(keyfile)-1 );
  1658.                 
  1659. #ifdef MSDOS
  1660.                 strlwr( keyfile     );
  1661. #endif
  1662.                 if (! file_exists( keyfile ))
  1663.                     default_extension( keyfile, PGP_EXTENSION );
  1664.  
  1665.                 if (! file_exists( keyfile ))
  1666.                 {    fprintf(pgpout, PSTR("\n\007Key file '%s' does not exist.\n"), keyfile );
  1667.                     errorLvl = NONEXIST_KEY_ERROR;
  1668.                     return -1;
  1669.                 }
  1670.  
  1671.                 workfile = keyfile;
  1672.  
  1673.             } else {
  1674.                 workfile = tempfile(TMP_WIPE|TMP_TMPDIR);
  1675.                 readPhantomInput(workfile);
  1676.             }
  1677.  
  1678.             if (myArgc < (filter_mode ? 3 : 4)) /* default key ring filename */
  1679.             {    byte ctb;
  1680.                 get_header_info_from_file(workfile, &ctb, 1);
  1681.                 if (ctb == CTB_CERT_SECKEY)
  1682.                     buildfilename(ringfile,SECRET_KEYRING_FILENAME);
  1683.                 else
  1684.                     buildfilename(ringfile,PUBLIC_KEYRING_FILENAME);
  1685.             }
  1686.             else
  1687.             {    strncpy( ringfile, myArgv[(filter_mode ? 2 : 3)], sizeof(ringfile)-1 );
  1688.                 default_extension( ringfile, PGP_EXTENSION );
  1689.             }
  1690. #ifdef MSDOS
  1691.             strlwr( ringfile );
  1692. #endif
  1693.  
  1694.             status = addto_keyring( workfile, ringfile);
  1695.  
  1696.             if (filter_mode)
  1697.                 rmtemp(workfile);
  1698.  
  1699.             if (status < 0)
  1700.             {    fprintf(pgpout, PSTR("\007Keyring add error. ") );
  1701.                 errorLvl = KEYRING_ADD_ERROR;
  1702.             }
  1703.             return status;
  1704.         }    /* Add key to key ring */
  1705.  
  1706.         /*-------------------------------------------------------*/
  1707.         case 'x':
  1708.         {    /*    Extract key from key ring
  1709.                 Arguments: mcguffin, keyfile, ringfile
  1710.             */
  1711.  
  1712.             if (myArgc >= (filter_mode ? 4 : 5))    /* default key ring filename */
  1713.                 strncpy( ringfile, myArgv[(filter_mode ? 3 : 4)], sizeof(ringfile)-1 );
  1714.             else
  1715.                 buildfilename( ringfile, PUBLIC_KEYRING_FILENAME );
  1716.  
  1717.             if (myArgc >= (filter_mode ? 2 : 3))
  1718.             {    if (myArgv[2])
  1719.                     /* Userid to extract */
  1720.                     strcpy( mcguffin, myArgv[2] );    
  1721.                 else
  1722.                     strcpy( mcguffin, "" );
  1723.             }
  1724.             else
  1725.             {
  1726.                 fprintf(pgpout, PSTR("\nA user ID is required to select the key you want to extract. "));
  1727.                 if (batchmode)    /* not interactive, userid must be on command line */
  1728.                     return -1;
  1729.                 fprintf(pgpout, PSTR("\nEnter the key's user ID: "));
  1730.                 getstring( mcguffin, 255, TRUE );    /* echo keyboard */
  1731.             }
  1732.             CONVERT_TO_CANONICAL_CHARSET(mcguffin);
  1733.  
  1734.             if (!filter_mode) {
  1735.                 if (myArgc >= 4)
  1736.                 {    strncpy( keyfile, myArgv[3], sizeof(keyfile)-1 );
  1737.                 }
  1738.                 else
  1739.                     keyfile[0] = '\0';
  1740.  
  1741.                 workfile = keyfile;
  1742.             } else {
  1743.                 workfile = tempfile(TMP_WIPE|TMP_TMPDIR);
  1744.             }
  1745.  
  1746. #ifdef MSDOS
  1747.             strlwr( workfile );
  1748.             strlwr( ringfile );
  1749. #endif
  1750.  
  1751.             default_extension( ringfile, PGP_EXTENSION );
  1752.  
  1753.             status = extract_from_keyring( mcguffin, workfile,
  1754.                     ringfile, (filter_mode ? FALSE :
  1755.                            emit_radix_64) );
  1756.  
  1757.             if (status < 0)
  1758.             {    fprintf(pgpout, PSTR("\007Keyring extract error. ") );
  1759.                 errorLvl = KEYRING_EXTRACT_ERROR;
  1760.                 if (filter_mode)
  1761.                     rmtemp(workfile);
  1762.                 return status;
  1763.             }
  1764.  
  1765.  
  1766.             if (filter_mode && !status) {
  1767.                 if (emit_radix_64)
  1768.                 {    /* NULL for outputfile means write to stdout */
  1769.                     if (armor_file(workfile, NULL, NULL, NULL) != 0)
  1770.                     {    errorLvl = UNKNOWN_FILE_ERROR;
  1771.                         return -1;
  1772.                     }
  1773.                 }
  1774.                 else
  1775.                     if (writePhantomOutput(workfile) < 0)
  1776.                     {    errorLvl = UNKNOWN_FILE_ERROR;
  1777.                         return -1;
  1778.                     }
  1779.                 rmtemp(workfile);
  1780.             }
  1781.  
  1782.             return 0;
  1783.         }    /* Extract key from key ring */
  1784.  
  1785.         /*-------------------------------------------------------*/
  1786.         case 'r':
  1787.         {    /*    Remove keys or selected key signatures from userid keys
  1788.                 Arguments: userid, ringfile
  1789.             */
  1790.  
  1791.             if (myArgc >= 4)
  1792.                 strcpy( ringfile, myArgv[3] );
  1793.             else    /* default key ring filename */
  1794.                 buildfilename( ringfile, PUBLIC_KEYRING_FILENAME );
  1795.  
  1796.             if (myArgc >= 3)
  1797.                 strcpy( mcguffin, myArgv[2] );    /* Userid to work on */
  1798.             else
  1799.             {    if (sign_flag)
  1800.                 {
  1801.                     fprintf(pgpout, PSTR("\nA user ID is required to select the public key you want to\n\
  1802. remove certifying signatures from. "));
  1803.                 }
  1804.                 else
  1805.                 {
  1806.                     fprintf(pgpout, PSTR("\nA user ID is required to select the key you want to remove. "));
  1807.                 }
  1808.                 if (batchmode)    /* not interactive, userid must be on command line */
  1809.                     return -1;
  1810.                 fprintf(pgpout, PSTR("\nEnter the key's user ID: "));
  1811.                 getstring( mcguffin, 255, TRUE );    /* echo keyboard */
  1812.             }
  1813.             CONVERT_TO_CANONICAL_CHARSET(mcguffin);
  1814.  
  1815. #ifdef MSDOS
  1816.             strlwr( ringfile );
  1817. #endif
  1818.             if (! file_exists( ringfile ))
  1819.                 default_extension( ringfile, PGP_EXTENSION );
  1820.  
  1821.             if (sign_flag)        /* Remove signatures */
  1822.             {    if (remove_sigs( mcguffin, ringfile ) < 0)
  1823.                 {    fprintf(pgpout, PSTR("\007Key signature remove error. ") );
  1824.                     errorLvl = KEYSIG_REMOVE_ERROR;
  1825.                     return -1;
  1826.                 }
  1827.             }
  1828.             else        /* Remove keyring */
  1829.             {    if (remove_from_keyring( NULL, mcguffin, ringfile, (boolean) (myArgc < 4) ) < 0)
  1830.                 {    fprintf(pgpout, PSTR("\007Keyring remove error. ") );
  1831.                     errorLvl = KEYRING_REMOVE_ERROR;
  1832.                     return -1;
  1833.                 }
  1834.             }
  1835.             return 0;
  1836.         }    /* remove key signatures from userid */
  1837.  
  1838.         /*-------------------------------------------------------*/
  1839.         case 'v':
  1840.         case 'V':        /* -kvv */
  1841.         {    /*    View or remove key ring entries, with userid match
  1842.                 Arguments: userid, ringfile
  1843.             */
  1844.  
  1845.             if (myArgc < 4) /* default key ring filename */
  1846.                 buildfilename( ringfile, PUBLIC_KEYRING_FILENAME );
  1847.             else
  1848.                 strcpy( ringfile, myArgv[3] );
  1849.  
  1850.             if (myArgc > 2)
  1851.             {    strcpy( mcguffin, myArgv[2] );
  1852.                 if (strcmp( mcguffin, "*" ) == 0)
  1853.                     mcguffin[0] = '\0';
  1854.             }
  1855.             else
  1856.                 *mcguffin = '\0';
  1857.  
  1858.             if ((myArgc == 3) && has_extension( myArgv[2], PGP_EXTENSION ))
  1859.             {    strcpy( ringfile, myArgv[2] );
  1860.                 mcguffin[0] = '\0';
  1861.             }
  1862.             CONVERT_TO_CANONICAL_CHARSET(mcguffin);
  1863.  
  1864. #ifdef MSDOS
  1865.             strlwr( ringfile );
  1866. #endif
  1867.             if (! file_exists( ringfile ))
  1868.                 default_extension( ringfile, PGP_EXTENSION );
  1869.  
  1870.             /* If a second 'v' (keychar = V), show signatures too */
  1871.             status = view_keyring(mcguffin, ringfile, (boolean) (keychar == 'V'), c_flag);
  1872.             if (status < 0)
  1873.             {    fprintf(pgpout, PSTR("\007Keyring view error. ") );
  1874.                 errorLvl = KEYRING_VIEW_ERROR;
  1875.             }
  1876.             return status;
  1877.         }    /* view key ring entries, with userid match */
  1878.  
  1879.         default:
  1880.             arg_error();
  1881.     }
  1882.     return 0;
  1883. } /* do_keyopt */
  1884.  
  1885.  
  1886.  
  1887. void user_error() /* comes here if user made a boo-boo. */
  1888. {
  1889.     fprintf(pgpout,PSTR("\nFor a usage summary, type:  pgp -h\n"));
  1890.     fprintf(pgpout,PSTR("For more detailed help, consult the PGP User's Guide.\n"));
  1891.     exitPGP(errorLvl ? errorLvl : 127);        /* error exit */
  1892. }
  1893.  
  1894. #if defined(DEBUG) && defined(linux)
  1895. #include <malloc.h>
  1896. #endif
  1897. /*
  1898.  * exitPGP: wipes and removes temporary files, also tries to wipe
  1899.  * the stack.
  1900.  */
  1901. void exitPGP(int returnval)
  1902. {
  1903.     char buf[STACK_WIPE];
  1904.     struct hashedpw *hpw;
  1905.  
  1906.     if (verbose)
  1907.         fprintf(pgpout, "exitPGP: exitcode = %d\n", returnval);
  1908.     for (hpw = passwds; hpw; hpw = hpw->next)
  1909.         memset(hpw->hash, 0, sizeof(hpw->hash));
  1910.     for (hpw = keypasswds; hpw; hpw = hpw->next)
  1911.         memset(hpw->hash, 0, sizeof(hpw->hash));
  1912.     cleanup_tmpf();
  1913. #if defined(DEBUG) && defined(linux)
  1914.     if (verbose)
  1915.     {    struct mstats mstat;
  1916.         mstat = mstats();
  1917.         printf("%d chunks used (%d bytes)  %d bytes total\n",
  1918.             mstat.chunks_used, mstat.bytes_used, mstat.bytes_total);
  1919.     }
  1920. #endif
  1921.     memset(buf, 0, sizeof(buf));    /* wipe stack */
  1922. #ifdef VMS
  1923. /*
  1924.  * Fake VMS style error returns with severity in bottom 3 bits
  1925.  */
  1926.     if (returnval)
  1927.         returnval = (returnval << 3) | 0x10000002;
  1928.     else
  1929.         returnval = 0x10000001;
  1930. #endif /* VMS */
  1931.     exit(returnval);
  1932. }
  1933.  
  1934.  
  1935. static void arg_error()
  1936. {
  1937.     signon_msg();
  1938.     fprintf(pgpout,PSTR("\nInvalid arguments.\n"));
  1939.     errorLvl = BAD_ARG_ERROR;
  1940.     user_error();
  1941. }
  1942.  
  1943. static void build_helpfile(char *helpfile)
  1944. {
  1945.     if (strcmp(language, "en"))
  1946.     {    buildfilename(helpfile, language);
  1947.         force_extension(helpfile, HLP_EXTENSION);
  1948.         if (!file_exists(helpfile))
  1949.             buildfilename(helpfile, HELP_FILENAME);
  1950.     }
  1951.     else
  1952.         buildfilename(helpfile, HELP_FILENAME);
  1953. }
  1954.  
  1955. static void usage()
  1956. {
  1957.     char helpfile[MAX_PATH];
  1958.     char *tmphelp = helpfile;
  1959.     extern unsigned char *ext_c_ptr;
  1960.  
  1961.     signon_msg();
  1962.     build_helpfile(helpfile);
  1963.   
  1964.     if (ext_c_ptr)
  1965.     {    /* conversion to external format necessary */
  1966.         tmphelp = tempfile(TMP_TMPDIR);
  1967.         CONVERSION = EXT_CONV;
  1968.         if (copyfiles_by_name(helpfile, tmphelp) < 0)
  1969.         {    rmtemp(tmphelp);
  1970.             tmphelp = helpfile;
  1971.         }
  1972.         CONVERSION = NO_CONV;
  1973.     }
  1974.  
  1975.       /* built-in help if pgp.hlp is not available */
  1976.     if (more_file(tmphelp) < 0)
  1977.         fprintf(pgpout,PSTR("\nUsage summary:\
  1978. \nTo encrypt a plaintext file with recipent's public key, type:\
  1979. \n   pgp -e textfile her_userid [other userids] (produces textfile.pgp)\
  1980. \nTo sign a plaintext file with your secret key:\
  1981. \n   pgp -s textfile [-u your_userid]           (produces textfile.pgp)\
  1982. \nTo sign a plaintext file with your secret key, and then encrypt it\
  1983. \n   with recipent's public key, producing a .pgp file:\
  1984. \n   pgp -es textfile her_userid [other userids] [-u your_userid]\
  1985. \nTo encrypt with conventional encryption only:\
  1986. \n   pgp -c textfile\
  1987. \nTo decrypt or check a signature for a ciphertext (.pgp) file:\
  1988. \n   pgp ciphertextfile [plaintextfile]\
  1989. \nTo produce output in ASCII for email, add the -a option to other options.\
  1990. \nTo generate your own unique public/secret key pair:  pgp -kg\
  1991. \nFor help on other key management functions, type:   pgp -k\n"));
  1992.     if (ext_c_ptr)
  1993.         rmtemp(tmphelp);
  1994.     exit(BAD_ARG_ERROR);        /* error exit */
  1995. }
  1996.  
  1997.  
  1998. static void key_usage()
  1999. {
  2000.     char helpfile[MAX_PATH];
  2001.  
  2002.     signon_msg();
  2003.     build_helpfile(helpfile);
  2004.     if (file_exists(helpfile))
  2005.     {    fprintf(pgpout,PSTR("\nFor a usage summary, type:  pgp -h\n"));
  2006.         fprintf(pgpout,PSTR("For more detailed help, consult the PGP User's Guide.\n"));
  2007.     }
  2008.     else    /* only use built-in help if there is no helpfile */
  2009.         fprintf(pgpout,PSTR("\nKey management functions:\
  2010. \nTo generate your own unique public/secret key pair:\
  2011. \n   pgp -kg\
  2012. \nTo add a key file's contents to your public or secret key ring:\
  2013. \n   pgp -ka keyfile [keyring]\
  2014. \nTo remove a key or a user ID from your public or secret key ring:\
  2015. \n   pgp -kr userid [keyring]\
  2016. \nTo edit your user ID or pass phrase:\
  2017. \n   pgp -ke your_userid [keyring]\
  2018. \nTo extract (copy) a key from your public or secret key ring:\
  2019. \n   pgp -kx userid keyfile [keyring]\
  2020. \nTo view the contents of your public key ring:\
  2021. \n   pgp -kv[v] [userid] [keyring]\
  2022. \nTo check signatures on your public key ring:\
  2023. \n   pgp -kc [userid] [keyring]\
  2024. \nTo sign someone else's public key on your public key ring:\
  2025. \n   pgp -ks her_userid [-u your_userid] [keyring]\
  2026. \nTo remove selected signatures from a userid on a keyring:\
  2027. \n   pgp -krs userid [keyring]\
  2028. \n"));
  2029.     exit(BAD_ARG_ERROR);        /* error exit */
  2030. }
  2031.